package com.wutu.nbyjk8.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Service
@Slf4j
public class EnergyService {


    @Value(value = "${energy.des}")
    private String energyDes;
    @Value(value = "${energy.uid}")
    private String energyUid;


    /**
     * 获取token
     *
     * @return
     */
    public String getToken() {
        String token = "";
        final long l = System.currentTimeMillis();
        try {
            String key = energyDes; // DES 密钥
            String originalData = energyUid + l; // 要加密的原始数据
            try {
                // 加密
                token = encrypt(originalData, key);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }


    private static final String ALGORITHM = "DES";
    private static final String TRANSFORMATION = "DES/ECB/PKCS5Padding"; // 使用 ECB 模式和 PKCS5 填充

    // 方法：进行 DES 加密
    public static String encrypt(String data, String key) throws Exception {
        // 创建密钥
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        DESKeySpec keySpec = new DESKeySpec(key.getBytes(StandardCharsets.UTF_8));
        SecretKey secretKey = keyFactory.generateSecret(keySpec);

        // 创建 Cipher 对象
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        // 加密数据
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData); // 返回 Base64 编码的字符串
    }

    // 方法：进行 DES 解密
    public static String decrypt(String encryptedData, String key) throws Exception {
        // 创建密钥
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        DESKeySpec keySpec = new DESKeySpec(key.getBytes(StandardCharsets.UTF_8));
        SecretKey secretKey = keyFactory.generateSecret(keySpec);

        // 创建 Cipher 对象
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        // 解密数据
        byte[] decodedData = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedData = cipher.doFinal(decodedData);
        return new String(decryptedData, StandardCharsets.UTF_8);
    }


}
